package Game;

import gui.StatisticPanel;

public class ArtificalLife extends Thread {
	public static boolean isEnd = false;
	volatile SpeciesLife yellowLife = new SpeciesLife(Species.YELLOW);
	volatile SpeciesLife redLife = new SpeciesLife(Species.RED);
	volatile SpeciesLife blackLife = new SpeciesLife(Species.BLACK);
	volatile SpeciesLife greenLife = new SpeciesLife(Species.GREEN);
	
    public void run(){

    	yellowLife.start();
    	redLife.start();
    	blackLife.start();
    	greenLife.start();
    	
    	while(!isEnd()) {

    		if(yellowLife.isReady() && redLife.isReady() && blackLife.isReady() && greenLife.isReady()) {
    			notifyAllLife();
    			Core.increaseGameAge();
    		}
    		
    		StatisticPanel.updateGame();
    	}
    	this.interrupt();
    	yellowLife.interrupt();
    	redLife.interrupt();
    	blackLife.interrupt();
    	greenLife.interrupt();
    }
    
    public void notifyAllLife() {
    //	System.out.println("budze");
		synchronized(yellowLife) {
    		if(yellowLife.getState() ==  Thread.State.WAITING) {
    			yellowLife.notify();	    			
    		}
		}
		
		synchronized(redLife) {
    		if(redLife.getState() ==  Thread.State.WAITING) {
    			redLife.notify();	    			
    		}
		}
		
		synchronized(greenLife) {
    		if(greenLife.getState() ==  Thread.State.WAITING) {
    			greenLife.notify();	    			
    		}
		}
		
		synchronized(blackLife) {
    		if(blackLife.getState() ==  Thread.State.WAITING) {
    			blackLife.notify();	    			
    		}
		}
    }
    
    public boolean isEnd() {
    	boolean y = true;
    	boolean r = true;
    	boolean g = true;
    	boolean b = true; 
    	if( Core.getAmountYellow() < 1) {
    		y = false;
    	}
    	
    	if( Core.getAmountRed() < 1) {
    		r = false;
    	}
    	
    	if( Core.getAmountGreen() < 1) {
    		g = false;
    	}
    	
    	if( Core.getAmountBlack() < 1) {
    		b = false;
    	}
		 
    	if(b && !y && !r && !g) {
    		StatisticPanel.showWin("czarne");
    		return true;
    	} else if(y && !b && !r && !g) {
    		StatisticPanel.showWin("zolte");
    		return true;
    	} else if(r && !y && !b && !g) {
    		StatisticPanel.showWin("czerwone");
    		return true;
    	} else if(g && !y && !r && !b) {
    		StatisticPanel.showWin("zielone");
    		return true;
    	}
    	
    	return false;
		
    }
}
